<%--
  Created by IntelliJ IDEA.
  User: oldliu
  Date: 2021/1/28
  Time: 16:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.io.*" language="java" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.util.UUID" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //request.setCharacterEncoding("utf-8");
    //String name=request.getParameter("sname");
    //String tel=request.getParameter("phone");
    //String card=request.getParameter("idcardpic");
    //out.print("姓名:"+name+",电话:"+tel+",身份证："+card);
//    InputStream in=request.getInputStream();
//    int ch=-1;
//    while((ch=in.read())!=-1){
//        out.print((char)ch);
//    }
%>
<%
   // boolean isuploadServletFileUpload.isMultipartContent(request);
    //if(is
    //cos
    FileItemFactory df=new DiskFileItemFactory();
    ServletFileUpload upload=new ServletFileUpload(df);
    upload.setHeaderEncoding("utf-8");
    List<FileItem> list=upload.parseRequest(request);
    String sname="",wechat="",qq="";
    for(FileItem fi:list){
        out.print("<hr/>");
        if(fi.isFormField()){
            out.print("这是一个普通的表单域，名字："+fi.getFieldName()+",值是："+fi.getString("utf-8"));
            switch (fi.getFieldName()){
                case "sname":
                    sname=fi.getString("utf-8");
                    break;
                case "qq":
                    qq=fi.getString("utf-8");
                    break;
                case "wechat":
                    wechat=fi.getString("utf-8");
                    break;
            }
        }else{
            out.print("这是一个文件域");
            if(fi.getSize()<1)
                continue;
            out.print("文件的名字是："+fi.getName()+",大小："+fi.getSize());
            //fi.get();
            String path=application.getRealPath("images");
            File parent=new File(path);
            if(parent.exists()==false)
                parent.mkdirs();
            //改名字
            String oldName=fi.getName();
            String prefix=oldName.substring(oldName.lastIndexOf('.'));
            String picName= UUID.randomUUID()+prefix;
            fi.write(new File(parent,picName));
            out.print(",文件保存在："+path+"/"+picName);
            //保存到db的路径怎么处理 images/xxx.png:
            //建议，存相对路径
            out.print("<img src='images/"+picName+"'/>");
        }
    }
%>
</body>
</html>
